package com.mxf.code.cases.order;

import com.alibaba.fastjson.JSON;
import com.mxf.code.mapper.MessageRecordMapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : MessageRecordServiceImpl
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/21 16:58]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/21 16:58]
 * @updateRemark : [描述说明本次修改内容]
 */
@Service
public class MessageRecordServiceImpl {
    @Autowired
    public MessageRecordMapper messageRecordMapper;

    @Autowired
    public RabbitmqServiceImpl rabbitmqService;

    @Autowired
    @Qualifier("si2")
    public RabbitmqServiceImpl2 si2;

    
    public boolean preCommit(MessageRecord messageRecord) {
        if (messageRecordMapper.insert(messageRecord) > 0) {
            return true;
        }
        return false;
    }

    
    public boolean commit(String messageId, boolean commitFlag) {
        /**
         * 不提交则代表回滚
         */
        if (!commitFlag) {
            messageRecordMapper.delByMessageId(messageId);
            return true;
        }
        // 提交消息到MQ
        MessageRecord messageRecord = messageRecordMapper.selectAllByMessageId(messageId);
        /**
         * 发送MQ消息
         * 将唯一消息ID设置给CorrelationData
         * 回调时可以用这个ID查找到数据对应的消息记录
         */
        rabbitmqService.sendMessage(OrderMQConfig.DIRECT_EXCHANGE_NAME, OrderMQConfig.DIRECT_ROUTING_KEY_NAME,
                JSON.toJSONString(messageRecord), new CorrelationData(messageRecord.getMessageId()));

        si2.sendMessage(OrderMQConfig2.DIRECT_EXCHANGE_NAME, OrderMQConfig2.DIRECT_ROUTING_KEY_NAME,
                JSON.toJSONString(messageRecord), new CorrelationData(messageRecord.getMessageId()));
        return true;
    }
    
    public void update(String messageId) {
        MessageRecord messageRecord = new MessageRecord();
        messageRecord.setMessageId(messageId);
        messageRecord.setStatus((byte) 1);
        messageRecordMapper.updateByMessageId(messageRecord);
    }
    
    public MessageRecord find(String messageId) {
        return messageRecordMapper.selectByPrimaryKey(Long.valueOf(messageId));
    }

    
    public List<MessageRecord> findAll(int status) {
        return messageRecordMapper.findAll(status);
        //return null;
    }
}
